<?php
// 应用公共文件

/**
 * Base64URL解码
 * @param string $data 欲解码数据
 * @return string $decode 解码后数据
 */
function base64url_decode($data)
{
    $data = str_replace(["", "-", "_"], ["=", "+", "/"], $data);
    $decode = base64_decode($data);
    return $decode;
}

/**
 * Base64URL编码
 * @param string $data 欲编码数据
 * @return string $encode 编码后数据
 */
function base64url_encode($data)
{
    $encode = base64_encode($data);
    $encode = str_replace(["=", "+", "/"], ["", "-", "_"], $encode);
    return $encode;
}

/**
 * 生成UUID
 * @param string $email 可选|根据email生成|已去敏
 * @return string $uuid
 */
function  uuid($email = null)
{
    if (!empty($email)) {
        $chars = md5(uniqid('byangforum' . $email));
    } else {
        $chars = md5(uniqid(random_bytes(32), true));
    }

    $uuid = substr($chars, 0, 8) . '-'
        . substr($chars, 8, 4) . '-'
        . substr($chars, 12, 4) . '-'
        . substr($chars, 16, 4) . '-'
        . substr($chars, 20, 12);
    return $uuid;
}

/**
 * 生成hash头像，使用gravatar提供服务
 * @param string $hash
 * @param int $size 默认120
 * @return string $avatarUrl 头像地址
 */
function generateAvatar($hash, $size = 120)
{
    return "https://www.gravatar.com/avatar/{$hash}?s={$size}&d=identicon";
}
